package cn.ljn.org.service.impl;

import cn.ljn.basic.service.BaseService;
import cn.ljn.basic.service.impl.BaseServiceImpl;
import cn.ljn.basic.util.AjaxResult;
import cn.ljn.basic.util.PageList;
import cn.ljn.org.domain.Department;
import cn.ljn.org.mapper.DepartmentMapper;
import cn.ljn.org.query.DepartmentQuery;
import cn.ljn.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper mapper;



        /**
         * 高级技师玩法 这种玩法你们必须掌握
         */
        @Override
        public List<Department> tree() {
            List<Department> result = new ArrayList<>();
            // 查询所有数据
            List<Department> allDepts = findAll();
            // 将allDepts 转成map   key：id    value：dept对象
            Map<Long, Department> deptMap = allDepts.stream().collect(Collectors.toMap(Department::getId, dept->dept));
            // 遍历集合
            for (Department dept : allDepts) {
                if (null == dept.getParentId()){
                    // 顶级部门
                    result.add(dept);
                }else {
                    Department parent = deptMap.get(dept.getParentId());
                    if (null != parent){
                        parent.getChildren().add(dept);
                    }

                }
            }
            return result;
    }


}
